package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.UserDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.exception.BusinessRuntimeException;
import com.itheima.pojo.SysUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

	@Autowired
	UserDao userDao;
	@Override
	public boolean login(String username, String password) {
		log.debug("service_provide...u:"+username+" p:"+password);
		if("admin".equals(username) && "123".equals(password)){
			return true;
		}else{
			throw new BusinessRuntimeException("登录失败");
		}
	}

	@Override
	public SysUser findByUsername(String username) {
		return userDao.findByUsername(username);
	}

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
		PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
		Page<SysUser> sysUsers =userDao.findPage(queryPageBean.getQueryString());
		return new PageResult(sysUsers.getTotal(), sysUsers.getResult());
	}

    @Override
    public SysUser finById(Integer id) {

		return userDao.findById(id);
    }

    @Override
    public void edit(Integer[] roleIds, SysUser user) {
		userDao.delRelation(user.getId());
        setRelation(user.getId(),roleIds);
        userDao.edit(user);
    }

	@Override
	public void add(Integer[] roleIds, SysUser user) {

		userDao.add(user);
		setRelation(user.getId(),roleIds);
	}

	@Override
	public void delById(Integer id) {
		userDao.delRelation(id);
        userDao.delById(id);
	}

	private void setRelation(Integer userId,Integer[] roleIds){
		if(roleIds != null && roleIds.length > 0){
			for (Integer roleId : roleIds) {
				userDao.setRelation(userId, roleId);
			}
		}
	}
}